package com.example.subsoilerwifi;

import android.content.Context;
import android.net.DhcpInfo;
import android.net.wifi.WifiManager;
import android.util.Log;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

public class SendDataUtils {
    private final static String TAG = "wifiApClient";
    private final static boolean LOCAL_DEBUG = true;
    private static InputStream mIn;
    private static OutputStream mOut;
    static Socket mSocket;
    private static final byte buf[] = new byte[1024];

    //获取连接热点的IP地址
    public static String getserverip(Context context) {
        WifiManager manager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
        DhcpInfo dhcpInfo = manager.getDhcpInfo();
        if (dhcpInfo == null)
            return "192.168.43.1";
        int ip = dhcpInfo.serverAddress;
        //整形转化为IP地址
        String sip = (ip & 0xff) + "." + ((ip >> 8) & 0xff) + "." + ((ip >> 16) & 0xff) + "." + ((ip >> 24) & 0xff);
        Log.e("服务器IP", sip);
        return sip;
    }

    public static boolean readFully(byte[] buffer, int len) {
        try {
            mIn.read(buffer, 0, len);
        } catch (IOException ioe) {
            Log.e(TAG, "read exception");
            disconnect();
            return false;
        }


        Log.e(TAG, "read " + len + " bytes");


        return true;
    }

    public static int readReply() {
        if (!readFully(buf, 2)) {
            return -1;
        }

        final int len = (((int) buf[0]) & 0xff) | ((((int) buf[1]) & 0xff) << 8);
        if ((len < 1) || (len > buf.length)) {
            Log.e(TAG, "invalid reply length (" + len + ")");
            disconnect();
            return -1;
        }

        if (!readFully(buf, len)) {
            return -1;
        }

        return len;
    }


    public static boolean writeCommand(String cmdString) {
        final byte[] cmd = cmdString.getBytes();
        final int len = cmd.length;
        if ((len < 1) || (len > buf.length)) {
            return false;
        }

        buf[0] = (byte) (len & 0xff);
        buf[1] = (byte) ((len >> 8) & 0xff);
        try {
            mOut.write(buf, 0, 2);
            mOut.write(cmd, 0, len);
        } catch (IOException ex) {
            Log.e(TAG, "write error");
            disconnect();
            return false;
        }
        return true;
    }


    public static void disconnect() {
        Log.i(TAG, "disconnecting...");
        try {
            if (mSocket != null)
                mSocket.close();
            if (mIn != null)
                mIn.close();
            if (mOut != null)
                mOut.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        mSocket = null;
        mIn = null;
        mOut = null;
    }

    public static boolean connect(Context context) {
        if (mSocket != null) {
            return true;
        }

        try {
            mSocket = new Socket(getserverip(context), 54321);
            mSocket.setSoTimeout(10 * 1000);
            Log.e("wifisocket", "建立连接");
            mIn = mSocket.getInputStream();
            mOut = mSocket.getOutputStream();
        } catch (IOException e) {
            disconnect();
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public static synchronized String transact(Context context, String cmd) {
        if (!connect(context)) {
            Log.e(TAG, "connection failed");
            return "-1";
        }

        if (!writeCommand(cmd)) {
            /*
             * If installd died and restarted in the background (unlikely but
             * possible) we'll fail on the next write (this one). Try to
             * reconnect and write the command one more time before giving up.
             */
            Log.e(TAG, "write command failed? reconnect!");
            if (!connect(context) || !writeCommand(cmd)) {
                return "-1";
            }
        }
        if (LOCAL_DEBUG) {
            Log.i(TAG, "send: '" + cmd + "'");
        }

        final int replyLength = readReply();
        if (replyLength > 0) {
            String s = new String(buf, 0, replyLength);
            if (LOCAL_DEBUG) {
                Log.i(TAG, "recv: '" + s + "'");
            }
            return s;
        } else {
            if (LOCAL_DEBUG) {
                Log.i(TAG, "fail");
            }
            return "-1";
        }
    }
}
